import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

// 一个简单的计数器Widget，用于演示SharedPreferences的使用
class SPCounterWidget extends StatefulWidget {
  const SPCounterWidget({super.key});

  @override
  State<SPCounterWidget> createState() => _SPCounterWidgetState();
}

class _SPCounterWidgetState extends State<SPCounterWidget> {
  String countString = '';
  String localCount = '';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('SharedPreferences计数器示例')),
      body: Column(
        children: [
          ElevatedButton(
            onPressed: _incrementCounter,
            child: const Text('增加计数'),
          ),
          ElevatedButton(onPressed: _getCounter, child: const Text('获取计数')),
          ElevatedButton(onPressed: _resetCounter, child: const Text('重置计数')),
          Text(countString, style: const TextStyle(fontSize: 20)),
          Text('result: $localCount', style: const TextStyle(fontSize: 20)),
        ],
      ),
    );
  }

  _incrementCounter() async {
    final prefs = await SharedPreferences.getInstance();
    setState(() {
      countString = '$countString 1';
    });
    int? counter = prefs.getInt('counter');
    counter = (counter ?? 0) + 1;
    await prefs.setInt('counter', counter);
  }

  _getCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    setState(() {
      localCount = prefs.getInt('counter').toString();
    });
  }

  _resetCounter() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setInt('counter', 0);
    setState(() {
      countString = '';
      localCount = '';
    });
  }
}
